<template>
	<view class="main">
		<view class="login" v-if="!isLogin">
			<uni-forms :modelValue="formData">
				<view class="quick-account">
					<view>账号选择：</view>
				    <uni-data-select
				      v-model="accountIndex"
				      :localdata="loginAccounts"
				      @change="change"
				    ></uni-data-select>
				  </view>
				<uni-forms-item required label="用户名" name="userName">
					<uni-easyinput type="text" v-model="formData.userName" placeholder="请输入用户名" />
				</uni-forms-item>
				<uni-forms-item required label="密码" name="password">
					<uni-easyinput type="password" v-model="formData.password" placeholder="请输入密码" />
				</uni-forms-item>
				
			</uni-forms>
			<view class="btn-box">
				<button type="primary" @click="login" >登陆</button>
			</view>
			
		</view>
		<view v-else class="account-box" >
			<!-- <view class="btn-box">
				<button type="primary" @click="sort" >排序</button>
			</view> -->
			<view v-for="(item,index) in accounts" :key="index" class="detail">
				<view class="first">
					<view class="left">{{index+1}}-客户：{{item.custName}}</view>
					<view class="right" style="color: red;">{{item.shuaKaCreditTrans || 0}}</view>
				</view>
				<view class="second">
					<view class="left">进度：
						<view class="grade" :class="'grade'+item.grade" >{{item.amount}}</view>
						<view v-if="item.unit==12">/1000</view>
						<view v-else style="color: red;">/10000</view>
					</view>
					<view class="middle">
						{{item.progress}}
					</view>
					<view class="right" :class="item.status=='EXPIRED'?'red':'green'">{{item.status}}</view>
				</view>
				<view class="third">
					<view class="right">当前周期：{{item.currentCycle}}</view>
					<view class="right">{{item.days || 0}}天</view>
				</view>
			</view>
		</view>
		<view class="buttom" v-if="isBottom">
			------已经到底了-------
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				baseData:{
					deviceType:'',
					osType:'Android',
					appCode:'JINKONG',
					appVersionCode:23,
					version:'1.8.5'
				},
				formData:{
					password:'ahao840811',
					userName:'19937679300'
				},
				loginUser:{},
				isLogin:false,
				accounts:[],
				page:1,
				totalSize: 0,
				isBottom:false,
				accountIndex:0,
				loginAccounts:[
					{value:0,text:'19937679300',userName:'19937679300',password:'ahao840811'},
					{value:1,text:'15639065213',userName:'15639065213',password:'ahao840811'},
					{value:2,text:'15238606638',userName:'15238606638',password:'ahao840811'},
					{value:3,text:'15981999880',userName:'15981999880',password:'19870527scj'},
					{value:4,text:'13838251280',userName:'13838251280',password:'546123abc'}
				]
			}
		},
		methods: {
			change(val){
				val = parseInt(val)
				if(val>=0){
					this.formData = this.loginAccounts[val];
				}else{
					this.formData = {}
				}
			},
			onNavigationBarButtonTap(event) {
				if(event.index==0){
					this.logOut()
				}else if(event.index==1){
					this.sort()
				}
			    
			},
			logOut(){
				this.page = 1
				this.totalSize=0
				this.accounts = []
				this.isLogin = false
			},
			sort(){
				this.accounts.sort(function(a,b){
					return a.days - b.days 
				})
				this.accounts.sort(function(a,b){
					return b.grade - a.grade 
				})
			},
			onPullDownRefresh(){
				this.page = 1
				this.getCurInfo()
				uni.stopPullDownRefresh()
			},
			// onReachBottom(){
			// 	this.isBottom = false
			// 	if(this.accounts.length >= this.totalSize){
			// 		 this.isBottom = true
			// 		 return
			// 	}
			// 	this.page++
			// 	this.getCurInfo()
			// },
			async getCurInfoAll(){
				let para = Object.assign({},this.baseData)
				para.loginKey = uni.getStorageSync("loginKey");
				para.page = this.page
				let that = this
				var res = await  this.$http.post('https://jinyingke.xingke.cn/opay-business/myBusiness/perCustInfo',para)
				res = res.data
				if(res.code == '0000'){ 
					let arr = res.data.subInfo
					if(arr.length > 0){
						uni.showLoading({
							title:'加载中...'
						})
						for(var i=0;i<arr.length;i++){
							var item = arr[i]
							that.getCurDetail(item)
						}
						uni.hideLoading()
					} 
				}else{
					uni.showToast({
						title:res.msg,
						icon:'error'
					})
					return
				}
			},
			getCurInfo(){
				if(this.page == 1){
					this.accounts = []
				}
				let para = Object.assign({},this.baseData)
				para.loginKey = uni.getStorageSync("loginKey");
				para.page = this.page
				let that = this
				this.$http.post('https://jinyingke.xingke.cn/opay-business/myBusiness/perCustInfo',para,res =>{
					if(res.code == '0000'){
						this.totalSize = res.data.totalCust
						let arr = res.data.subInfo
						if(arr.length > 0){
							uni.showLoading({
								title:'加载中...'
							})
							for(var i=0;i<arr.length;i++){
								var item = arr[i]
								that.getCurDetail(item)
							}
							uni.hideLoading()
						}
						
						 let totalPage = this.totalSize / 10 == 0 ? this.totalSize / 10 : this.totalSize / 10 + 1
						 for(var i=2;i<totalPage;i++){
							 that.page = i
							 that.getCurInfoAll()
						 }
						that.sort()
					}else{
						uni.showToast({
							title:res.msg,
							icon:'error'
						})
						return
					}
				})
			},
			async getCurDetail(item){
				let para = {
					loginKey:uni.getStorageSync('loginKey'),
					customerNo:item.customerNo
				}
				var res = await this.$http.post('https://jinyingke.xingke.cn/opay-business/myBusiness/custTransInfo',para)
				var res = res.data
				if(res.code=='0000'){
					var data = res.data
					if(data.customerAwardType){
						var qh = data.customerAwardType.replace('CUST_AWARD_','');
						data.unit = qh
					}else{
						data.unit = ''
					}
					
					if(data.progress){
						data.progress = data.progress.replace("S","") + '/' + qh;
					} 
					item = Object.assign(item,data)
					var grade = this.getGrade(item)
					item.grade = grade
					this.accounts.push(item)
				}
			},
			getGrade(item){
				var grade = 0;
				if(item.status=='EXPIRED'){
					grade = -6
					item.days = 999
				}else if(item.status=="NOT_PARTICIPATE"){
					grade = 7
					item.amount = 0
					item.days = 0
				}else{
					if(item.currentCycle){
						var dates = item.currentCycle.split('~');
						if(dates && dates.length==2){
							var endDate = new Date(dates[1])
							var curDate = new Date()
							var days = this.getDaysBetween(endDate,curDate)
							item.days = days
							var baseMoney = item.unit == 12 ? 1000 : 10000
							if(item.amount < baseMoney){
								if(days >= 20){
									grade = 1
								}else if(days >= 10){
									grade = 2
								}else if(days >=5){
									grade = 3
								}else if(days >= 3){
									grade = 4
								}else if(days >=0){
									grade = 5
								}
							}
						}
					}
				}
				return grade;
			},
			getDaysBetween(date1, date2) {
			  const ONE_DAY = 1000 * 60 * 60 * 24; // 一天的毫秒数
			  const date1Time = date1.getTime(); // 获取时间戳
			  const date2Time = date2.getTime();
			
			  const difference = Math.abs(date1Time - date2Time); // 获取时间差
			  return Math.round(difference / ONE_DAY); // 两个日期之间的天数
			},
			login(){
				this.isLogin = false 
				let para = Object.assign({},this.formData)
				para = Object.assign(para,this.baseData)
				para.sign = this.getSignData(para)	
				this.$http.post('https://jinyingke.xingke.cn/opay-business/user/signIn',para,res =>{
					if(res.code == '0000'){
						 this.loginUser = res.data
						 uni.setStorageSync("loginKey",this.loginUser.loginKey)
						 this.isLogin = true;
						 this.getCurInfo()
					}else{
						uni.showToast({
							title:res.msg,
							icon:'error'
						})
						return
					}
				})
			},
			getSignData(para){
				var signData = this.useMd5(this.jsonToArray(para)) 
				return signData;
			},
			jsonToArray(json) {
			    var arr = [];
			    for (var i in json) {
			
			        var baseType = "";
			        var toString = "";
			
			        try {
			            baseType = JSON.parse(json[i]);
			        } catch (e) {
			            baseType = json[i];
			        }
			
					toString = '{"' + i + '":"' + json[i] + '"}';
			
			        var toJson = JSON.parse(toString);
			        arr.push(toJson);
			    }
			
			    return arr;
			},
			useMd5(array) {
			    var signKey = '86eb1492-6e08-481d-b377-678acd5c3de5';
			    var resultString = "";
			    if (array.length > 0) {
			        var parmas = [];
			        var resultArray = [];
			        for (var i = 0; i < array.length; i++) {
			            for (var key in array[i]) {
			                parmas.push(key);
			            }
			        }
			        for (var _i = 0; _i < parmas.sort(function (a, b) {
			            if (a.toString().toLowerCase() > b.toString().toLowerCase()) {
			                return 1;
			            } else {
			                return -1;
			            }
			        }).length; _i++) {
			            for (var j = 0; j < array.length; j++) {
			                for (var _key in array[j]) {
			                    if (parmas[_i] == _key) {
			                        if (Array.isArray(array[j][_key])) {
			                            array[j][_key] = JSON.stringify(array[j][_key]);
			                        }
			                        resultArray.push(array[j]);
			                    }
			                }
			            }
			        }
			
			        resultArray.map(function (el, index) {
			            for (var _key2 in el) {
			                resultString += _key2 + "=" + el[_key2];
			            }
			        });
			    }
			    return this.$md5.hex_md5_32(resultString + signKey);
			}
		}
	}
</script>

<style lang="scss" scoped>
.quick-account{
	display: flex;
	align-items: center;
	height: 72upx;
	margin-bottom: 20upx;
}
.login{
	padding-top: 40rpx;
	width: 500rpx;
	margin: 0px auto;
	display: block;
}
.account-box{
	width: 750rpx;
	overflow: auto;
	padding: 30rpx;
	.btn-box{
		display: block;
		width: 500rpx;
		margin: 0 auto;
	}
	.detail{
		width: 690rpx;
		border-bottom: 1px solid #e2e2e2;
		padding-bottom: 30rpx;
		padding-top: 20rpx;
		.first{
			height: 50rpx;
			display: flex;
			justify-content: space-between;
		}
		.second{
			height: 50rpx;
			display: flex;
			justify-content: space-between;
			.left{
				display: flex;
			}
			.red{
				color: #ff0000;
			}
			.green{
				color: #00ff00;
			}
		}
		.third{
			display: flex;
			justify-content: space-between;
		}
	}
	
}
.buttom{
		text-align: center;
		color: #e2e2e2;
	}
.grade0{
	color: #000000!important;
}
.grade{
	min-width: 100rpx;
	color: #ffffff;
	text-align: center;
	height: 36rpx;
}
.grade1{
	background-color: #fca7ba;
}
.grade2{
	background-color: #ff4069;
}
.grade3{
	background-color: #ed0606;
}
.grade4{
	background-color: #c90505;
}
.grade5{
	background-color: #930101;
}
.grade-6{
	background-color: #bdc8b3;
}
.grade7{
	background-color: #aa55ff;
}
</style>
